package com.peng.leetcode.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * TreeToDoublyList
 *
 * @author: lupeng6
 * @create: 2021/3/1 16:00
 */
public class TreeToDoublyList {

    public static void main(String[] args) {

    }

    private Queue<Node> queue = new LinkedList<>();

    public Node treeToDoublyList(Node root) {
        if (root == null) {
            return null;
        }
        inOrder(root);

        Node node = queue.poll();
        Node temp = node;
        while (!queue.isEmpty()) {
            Node curr = queue.poll();
            node.right = curr;
            curr.left = node;
            node = curr;
        }
        node.right = temp;
        temp.left = node;
        return temp;
    }

    private void inOrder(Node node) {
        if (node == null) {
            return;
        }
        inOrder(node.left);
        queue.offer(node);
        inOrder(node.right);
    }


    static class Node {
        public int val;
        public Node left;
        public Node right;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right) {
            val = _val;
            left = _left;
            right = _right;
        }
    }
}
